<template>
  <view class="points-detail-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <uni-icons 
        type="arrowleft" 
        size="24" 
        color="#333" 
        @click="goBack"
      ></uni-icons>
      <view class="nav-title">商品详情</view>
      <view class="nav-right">
        <uni-icons type="share" size="20" color="#333" @click="shareProduct"></uni-icons>
      </view>
    </view>
    
    <!-- 商品图片轮播 -->
    <swiper class="product-swiper" :autoplay="autoplay" circular>
      <swiper-item v-for="(img, index) in product.images" :key="index">
        <image class="swiper-image" :src="img" mode="aspectFill"></image>
      </swiper-item>
    </swiper>
    <view class="swiper-indicator">
      <text>{{ currentImageIndex + 1 }}/{{ product.images.length }}</text>
    </view>
    
    <!-- 商品基本信息 -->
    <view class="product-base-info">
      <view class="price-section">
        <text class="points-value">{{ product.points }}</text>
        <text class="points-unit">积分</text>
        <text class="original-price" v-if="product.originalPrice">市场价: ¥{{ product.originalPrice }}</text>
      </view>
      <view class="product-name">
        <text>{{ product.name }}</text>
      </view>
      <view class="product-desc">
        <text>{{ product.desc }}</text>
      </view>
      <view class="product-meta">
        <view class="meta-item">
          <text>销量 {{ product.sales }}</text>
        </view>
        <view class="meta-item">
          <text>库存 {{ product.stock }}件</text>
        </view>
        <view class="meta-item">
          <text>兑换 {{ product.exchanges }}次</text>
        </view>
      </view>
    </view>
    
    <!-- 商品规格选择 -->
    <view class="product-spec" v-if="product.specs && product.specs.length > 0">
      <view class="section-title">
        <text>规格选择</text>
      </view>
      <view class="spec-list">
        <view 
          class="spec-item" 
          v-for="spec in product.specs" 
          :key="spec.id"
          :class="{active: selectedSpecId === spec.id}"
          @click="selectSpec(spec.id)"
        >
          <text>{{ spec.name }}</text>
        </view>
      </view>
    </view>
    
    <!-- 商品详情 -->
    <view class="product-detail">
      <view class="section-title">
        <text>商品详情</text>
      </view>
      <rich-text :nodes="product.detail"></rich-text>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="action-left">
        <view class="action-icon" @click="toggleFavorite">
          <uni-icons 
            :type="isFavorite ? 'heart-filled' : 'heart'" 
            size="24" 
            :color="isFavorite ? '#F44336' : '#666'"
          ></uni-icons>
          <text>{{ isFavorite ? '已收藏' : '收藏' }}</text>
        </view>
        <view class="action-icon" @click="goHome">
          <uni-icons type="home" size="24" color="#666"></uni-icons>
          <text>首页</text>
        </view>
      </view>
      <view class="action-right">
        <button 
          class="exchange-btn" 
          :class="{disabled: product.stock <= 0 || userPoints < product.points}"
          :disabled="product.stock <= 0 || userPoints < product.points"
          @click="showExchangePopup"
        >
          {{ getExchangeBtnText }}
        </button>
      </view>
    </view>
    
    <!-- 兑换弹窗 -->
    <uni-popup ref="exchangePopup" type="bottom">
      <view class="exchange-popup">
        <view class="popup-header">
          <text class="title">确认兑换</text>
          <uni-icons type="close" size="24" color="#999" @click="closeExchangePopup"></uni-icons>
        </view>
        <view class="popup-content">
          <view class="product-info">
            <image class="product-image" :src="product.images[0]" mode="aspectFill"></image>
            <view class="info-right">
              <text class="product-name">{{ product.name }}</text>
              <view class="product-points">
                <text class="points-value">{{ product.points }}</text>
                <text class="points-unit">积分</text>
              </view>
              <text class="stock" v-if="product.stock > 0">剩余{{ product.stock }}件</text>
              <text class="stock empty" v-else>已兑完</text>
            </view>
          </view>
          <view class="user-points">
            <text>我的积分: {{ userPoints }}分</text>
            <text class="points-after" v-if="userPoints >= product.points">
              兑换后剩余: {{ userPoints - product.points }}分
            </text>
            <text class="points-after error" v-else>
              还需{{ product.points - userPoints }}分
            </text>
          </view>
          <view class="address-section" v-if="product.type === 'physical'">
            <view class="section-title">
              <text>收货信息</text>
              <text class="change-address" @click="changeAddress">修改</text>
            </view>
            <view class="address-info" v-if="defaultAddress">
              <view class="address-row">
                <text class="receiver">{{ defaultAddress.receiver }}</text>
                <text class="phone">{{ defaultAddress.phone }}</text>
              </view>
              <view class="address-detail">
                <text>{{ defaultAddress.province }}{{ defaultAddress.city }}{{ defaultAddress.district }}{{ defaultAddress.detail }}</text>
              </view>
            </view>
            <view class="no-address" v-else @click="changeAddress">
              <text>请添加收货地址</text>
              <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <button 
            class="confirm-btn" 
            :class="{disabled: product.stock <= 0 || userPoints < product.points || (product.type === 'physical' && !defaultAddress)}"
            :disabled="product.stock <= 0 || userPoints < product.points || (product.type === 'physical' && !defaultAddress)"
            @click="confirmExchange"
          >
            确认兑换
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 商品数据
const product = ref({
  id: '',
  name: '',
  desc: '',
  points: 0,
  originalPrice: '',
  type: 'virtual', // virtual / physical
  images: [],
  sales: 0,
  stock: 0,
  exchanges: 0,
  specs: [],
  detail: ''
})

// 用户数据
const userPoints = ref(3560)
const isFavorite = ref(false)
const defaultAddress = ref(null)

// 选择规格
const selectedSpecId = ref('')
const currentImageIndex = ref(0)
const autoplay = ref(false)

// 弹窗引用
const exchangePopup = ref(null)

// 计算属性
const getExchangeBtnText = computed(() => {
  if (product.value.stock <= 0) return '已兑完'
  if (userPoints.value < product.value.points) return `还需${product.value.points - userPoints.value}积分`
  return '立即兑换'
})

// 页面加载
onLoad((options) => {
  if (options.id) {
    // 根据ID获取商品详情
    fetchProductDetail(options.id)
    // 获取用户地址
    fetchDefaultAddress()
    // 检查是否收藏
    checkFavorite()
  }
})

// 获取商品详情
const fetchProductDetail = (id) => {
  // 模拟API请求
  setTimeout(() => {
    // 模拟数据
    product.value = {
      id: id,
      name: '50元京东E卡电子兑换码',
      desc: '京东商城通用电子礼品卡，可自用或赠与他人',
      points: 5000,
      originalPrice: '50.00',
      type: 'virtual',
      images: [
        '/static/images/product-jd-card.jpg',
        '/static/images/product-jd-card-2.jpg',
        '/static/images/product-jd-card-3.jpg'
      ],
      sales: 125,
      stock: 56,
      exchanges: 89,
      specs: [
        { id: '1', name: '50元面值' },
        { id: '2', name: '100元面值' },
        { id: '3', name: '200元面值' }
      ],
      detail: `
        <div style="padding:20px;">
          <h3>商品详情</h3>
          <p>京东E卡是京东商城发行的预付卡，可用于购买京东商城所有商品</p>
          <img src="/static/images/product-jd-card-detail.jpg" style="width:100%;"/>
          <h3>使用说明</h3>
          <p>1. 兑换成功后，电子兑换码将发送至您的账户</p>
          <p>2. 登录京东账号，进入"我的钱包"-"礼品卡"-"绑定新卡"</p>
          <p>3. 输入兑换码完成绑定，余额可用于购物</p>
          <h3>注意事项</h3>
          <p>1. 电子卡有效期为3年</p>
          <p>2. 不记名不挂失，请妥善保管</p>
          <p>3. 不可兑现，不找零</p>
        </div>
      `
    }
    selectedSpecId.value = product.value.specs[0].id
  }, 500)
}

// 获取默认地址
const fetchDefaultAddress = () => {
  // 模拟API请求
  setTimeout(() => {
    // 模拟数据
    defaultAddress.value = {
      id: '1',
      receiver: '张三',
      phone: '13800138000',
      province: '北京市',
      city: '北京市',
      district: '朝阳区',
      detail: '建国路88号现代城A座1001室'
    }
  }, 300)
}

// 检查是否收藏
const checkFavorite = () => {
  // 模拟API请求
  setTimeout(() => {
    isFavorite.value = Math.random() > 0.5
  }, 300)
}

// 选择规格
const selectSpec = (specId) => {
  selectedSpecId.value = specId
}

// 切换收藏状态
const toggleFavorite = () => {
  isFavorite.value = !isFavorite.value
  uni.showToast({
    title: isFavorite.value ? '已收藏' : '已取消收藏',
    icon: 'none'
  })
  // 实际项目中这里应该调用API更新收藏状态
}

// 显示兑换弹窗
const showExchangePopup = () => {
  if (product.value.stock <= 0) {
    uni.showToast({
      title: '该商品已兑完',
      icon: 'none'
    })
    return
  }
  
  if (userPoints.value < product.value.points) {
    uni.showToast({
      title: `积分不足，还需${product.value.points - userPoints.value}积分`,
      icon: 'none'
    })
    return
  }
  
  exchangePopup.value.open()
}

// 关闭兑换弹窗
const closeExchangePopup = () => {
  exchangePopup.value.close()
}

// 确认兑换
const confirmExchange = () => {
  if (product.value.type === 'physical' && !defaultAddress.value) {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none'
    })
    return
  }
  
  uni.showLoading({
    title: '兑换中...'
  })
  
  // 模拟API请求
  setTimeout(() => {
    uni.hideLoading()
    exchangePopup.value.close()
    uni.navigateTo({
      url: `/pages/points/exchange-success?id=${product.value.id}`
    })
  }, 1500)
}

// 修改地址
const changeAddress = () => {
  uni.navigateTo({
    url: '/pages/address/list?from=points'
  })
}

// 分享商品
const shareProduct = () => {
  uni.share({
    provider: 'weixin',
    type: 0,
    title: `【积分兑换】${product.value.name}`,
    summary: `仅需${product.value.points}积分即可兑换，快来参与吧！`,
    href: `https://www.yoursite.com/points/detail?id=${product.value.id}`,
    imageUrl: product.value.images[0],
    success: () => {
      uni.showToast({
        title: '分享成功',
        icon: 'success'
      })
    }
  })
}

// 返回首页
const goHome = () => {
  uni.switchTab({
    url: '/pages/index/index'
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>

.points-detail-container {
  padding-bottom: 120rpx;
  background-color: $white-bg;
  min-height: 100vh;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background-color: rgba(255, 255, 255, 0.9);
  z-index: 10;
  
  .nav-title {
    font-size: $font-size-32rpx;
    font-weight: bold;
    color: $text-color;
  }
  
  .nav-right {
    width: 40rpx;
  }
}

.product-swiper {
  width: 100%;
  height: 750rpx;
  
  .swiper-image {
    width: 100%;
    height: 100%;
  }
}

.swiper-indicator {
  position: absolute;
  top: 700rpx;
  right: 30rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: $text-color-inverse;
  font-size: $font-size-24rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
}

.product-base-info {
  padding: 30rpx;
  
  .price-section {
    display: flex;
    align-items: flex-end;
    margin-bottom: 20rpx;
    
    .points-value {
      font-size: 48rpx;
      font-weight: bold;
      color: $primary-color;
    }
    
    .points-unit {
      font-size: $font-size-28rpx;
      color: $primary-color;
      margin: 0 20rpx 0 10rpx;
    }
    
    .original-price {
      font-size: $font-size-24rpx;
      color: $text-color-666;
      text-decoration: line-through;
    }
  }
  
  .product-name {
    font-size: $font-size-34rpx;
    font-weight: bold;
    color: $text-color;
    margin-bottom: 20rpx;
  }
  
  .product-desc {
    font-size: $font-size-28rpx;
    color: $text-color-666;
    margin-bottom: 30rpx;
  }
  
  .product-meta {
    display: flex;
    
    .meta-item {
      font-size: $font-size-24rpx;
      color: $text-color-666;
      margin-right: 30rpx;
    }
  }
}

.section-title {
  font-size: $font-size-30rpx;
  font-weight: bold;
  color: $text-color;
  padding: 30rpx;
  border-top: 20rpx solid $light-bg;
  border-bottom: 1rpx solid #f5f5f5;
}

.product-spec {
  .spec-list {
    display: flex;
    flex-wrap: wrap;
    padding: 0 30rpx 30rpx;
    
    .spec-item {
      padding: 16rpx 30rpx;
      margin-right: 20rpx;
      margin-bottom: 20rpx;
      font-size: $font-size-26rpx;
      color: $text-color;
      background-color: $light-bg;
      border-radius: 30rpx;
      border: 1rpx solid #eee;
      
      &.active {
        color: $primary-color;
        border-color: $primary-color;
        background-color: rgba(255, 140, 0, 0.1);
      }
    }
  }
}

.product-detail {
  padding-bottom: 30rpx;
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 100rpx;
  background-color: $white-bg;
  border-top: 1rpx solid #f5f5f5;
  z-index: 10;
  
  .action-left {
    display: flex;
    align-items: center;
    width: 40%;
    
    .action-icon {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      
      text {
        font-size: $font-size-20rpx;
        color: $text-color-666;
        margin-top: 6rpx;
      }
    }
  }
  
  .action-right {
    flex: 1;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    
    .exchange-btn {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      font-size: $font-size-30rpx;
      color: $text-color-inverse;
      background-color: $primary-color;
      border-radius: 40rpx;
      
      &.disabled {
        background-color: #ccc;
      }
    }
  }
}

.exchange-popup {
  background-color: $white-bg;
  border-radius: 30rpx 30rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    .title {
      font-size: $font-size-32rpx;
      font-weight: bold;
      color: $text-color;
    }
  }
  
  .popup-content {
    padding: 30rpx;
    
    .product-info {
      display: flex;
      margin-bottom: 40rpx;
      
      .product-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }
      
      .info-right {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        
        .product-name {
          font-size: $font-size-28rpx;
          color: $text-color;
          @include text-ellipsis(2);
        }
        
        .product-points {
          .points-value {
            font-size: $font-size-32rpx;
            color: $primary-color;
            font-weight: bold;
          }
          
          .points-unit {
            font-size: $font-size-24rpx;
            color: $primary-color;
            margin-left: 6rpx;
          }
        }
        
        .stock {
          font-size: $font-size-24rpx;
          color: $text-color-666;
          
          &.empty {
            color: #F44336;
          }
        }
      }
    }
    
    .user-points {
      padding: 25rpx 0;
      border-top: 1rpx solid #f5f5f5;
      border-bottom: 1rpx solid #f5f5f5;
      margin-bottom: 30rpx;
      
      text {
        display: block;
        font-size: $font-size-26rpx;
        color: $text-color;
        margin-bottom: 10rpx;
      }
      
      .points-after {
        font-size: $font-size-24rpx;
        color: $primary-color;
        
        &.error {
          color: #F44336;
        }
      }
    }
    
    .address-section {
      .section-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: $font-size-28rpx;
        color: $text-color;
        padding: 0 0 20rpx;
        border: none;
        
        .change-address {
          font-size: $font-size-24rpx;
          color: $primary-color;
        }
      }
      
      .address-info {
        background-color: $light-bg;
        border-radius: 8rpx;
        padding: 20rpx;
        
        .address-row {
          display: flex;
          align-items: center;
          margin-bottom: 10rpx;
          
          .receiver {
            font-size: $font-size-28rpx;
            color: $text-color;
            margin-right: 20rpx;
          }
          
          .phone {
            font-size: $font-size-26rpx;
            color: $text-color-666;
          }
        }
        
        .address-detail {
          font-size: $font-size-26rpx;
          color: $text-color-666;
        }
      }
      
      .no-address {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: $light-bg;
        border-radius: 8rpx;
        padding: 30rpx 20rpx;
        font-size: $font-size-26rpx;
        color: $text-color-666;
      }
    }
  }
  
  .popup-footer {
    padding: 0 30rpx 30rpx;
    
    .confirm-btn {
      width: 100%;
      height: 90rpx;
      line-height: 90rpx;
      font-size: $font-size-32rpx;
      color: $text-color-inverse;
      background-color: $primary-color;
      border-radius: 45rpx;
      
      &.disabled {
        background-color: #ccc;
      }
    }
  }
}
</style>